<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只能选择三级分类下添加属性"
        type="warning" show-icon :closable="false">
      </el-alert>
      <el-row class="cat_opt">
        <el-col><span>选择商品分类：</span>
          <el-cascader
            v-model="selectCateKay"
            :options="cateList"
            :props="{ expandTrigger: 'hover',
             value: 'cat_id',
             label: 'cat_name',
             children: 'children',
             checkStrictly: true}"
            @change="handleChange"></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisable" @click="addDialogVisible = true">添加参数</el-button>
          <el-table
            :data="cateManyData"
            stripe
            border
            style="width: 100%">
            <el-table-column
              type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable class="attr_val" @close="removeAttr(i,scope.row)">
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
              label="id"
              type="index">
            </el-table-column>
            <el-table-column
              prop="attr_name"
              label="名称">
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditCateParams(scope.row)">编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="delCateParams(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisable" @click="addDialogVisible = true">添加属性</el-button>
          <el-table
            :data="cateOnlyData"
            stripe
            border
            style="width: 100%">
            <el-table-column
              type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable class="attr_val" @close="removeAttr(i,scope.row)">
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
              label="id"
              type="index">
            </el-table-column>
            <el-table-column
              prop="attr_name"
              label="名称">
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditCateParams(scope.row)">编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="delCateParams(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :title="'添加'+aTitle"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addDialogClosed">
      <el-form :model="addParamsForm" :rules="addParamsRules" ref="addParamsFormRef" label-width="100px">
        <el-form-item :label="aTitle" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateParams">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="'修改'+aTitle"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClosed">
      <el-form :model="editParamsForm" :rules="editParamsRules" ref="editParamsFormRef" label-width="100px">
        <el-form-item :label="aTitle" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      cateList: [],
      selectCateKay: [],
      activeName: 'many',
      cateOnlyData: [],
      cateManyData: [],
      addDialogVisible: false,
      addParamsForm: {
        attr_name: ''
      },
      addParamsRules: {
        attr_name: [{
          required: true,
          message: '请输入活动名称',
          trigger: 'blur'
        }]
      },
      editDialogVisible: false,
      editParamsForm: {},
      editParamsRules: {
        attr_name: [{
          required: true,
          message: '请输入活动名称',
          trigger: 'blur'
        }]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
      // console.log(this.cateList)
    },
    handleChange () {
      this.cateOnlyData = []
      this.cateManyData = []
      this.getCateParams()
    },
    async getCateParams () {
      if (this.selectCateKay.length === 3) {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // console.log(res.data)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length !== 0 ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        if (this.activeName === 'only') {
          this.cateOnlyData = res.data
        } else if (this.activeName === 'many') {
          this.cateManyData = res.data
        }
      }
    },
    handleTabsClick () {
      this.getCateParams()
      // console.log(this.activeName)
    },
    addDialogClosed () {
      this.$refs.addParamsFormRef.resetFields()
    },
    addCateParams () {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName,
          attr_vals: this.addParamsForm.attr_vals
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getCateParams()
        this.addDialogVisible = false
      })
    },
    editDialogClosed () {
      this.$refs.editParamsFormRef.resetFields()
    },
    async showEditCateParams (cateData) {
      const { data: res } = await this.$http.get(`categories/${cateData.cat_id}/attributes/${cateData.attr_id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editParamsForm = res.data
      this.editDialogVisible = true
    },
    editCateParams () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.editParamsForm.cat_id}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName,
          attr_vals: this.editParamsForm.attr_vals
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getCateParams()
        this.editDialogVisible = false
      })
    },
    delCateParams (cateData) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return this.$http.delete(`categories/${cateData.cat_id}/attributes/${cateData.attr_id}`)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }).then(({ data: res }) => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getCateParams()
      })
    },
    removeAttr (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    },
    async saveAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm (row) {
      console.log(row.inputValue)
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    }
  },
  computed: {
    isBtnDisable () {
      if (this.selectCateKay.length === 3) {
        return false
      } else {
        return true
      }
    },
    cateId () {
      if (this.selectCateKay.length === 3) {
        return this.selectCateKay[this.selectCateKay.length - 1]
      } else {
        return null
      }
    },
    aTitle () {
      if (this.activeName === 'only') {
        return '静态属性'
      } else {
        return '动态参数'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
}

.attr_val {
  margin-right: 5px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
